import type { UseFetchOptions } from 'nuxt/app'

const router = useRouter()
const logout = function () {
  router.push({ path: '/login' })
}

type Methods = 'GET' | 'POST' | 'DELETE' | 'PUT'

const BASE_URL = ''

export interface IResultData<T> {
  code: number
  data: T
  msg: string
  success: boolean
}

class HttpRequest {
  async request<T>(
    url: string,
    method: Methods,
    data: any,
    options?: UseFetchOptions<T>,
  ) {
    await nextTick() // 解决刷新页面useFetch无返回
    return new Promise((resolve, reject) => {
      const headers: any = {}
      const authToken = sessionStorage.getItem('access_token')
      if (authToken != null)
        headers.Authorization = `Bearer ${authToken}`

      const defaultOptions: UseFetchOptions<T> = {
        baseURL: BASE_URL,
        method,
        headers,
        // 响应拦截
        /* eslint-disable-next-line unused-imports/no-unused-vars */
        onResponse({ response }: { response: Response }) {
          // console.log("response", response);
        },
        // 响应错误拦截
        onResponseError({ response }: { response: Response }) {
          // 后端返回401时导航到登录界面
          if (response.status === 401) {
            // todo
            logout()
          }
        },
      }
      const newOptions: any = { ...defaultOptions, ...options }

      if (method === 'GET' || method === 'DELETE')
        newOptions.params = data

      if (method === 'POST' || method === 'PUT')
        newOptions.body = data

      $fetch(url, newOptions)
        .then((response: any) => {
          try {
            if (typeof response === 'string')
              response = JSON.parse(response)
          }
          catch (error: any) {
            // eslint-disable-next-line no-console
            console.log(error)
          }

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 封装常用方法
  get<P, T>(url: string, params?: P, options?: UseFetchOptions<T>) {
    return this.request(url, 'GET', params, options)
  }

  post<P, T>(url: string, data: P, options?: UseFetchOptions<T>) {
    return this.request(url, 'POST', data, options)
  }

  Put<P, T>(url: string, data: P, options?: UseFetchOptions<T>) {
    return this.request(url, 'PUT', data, options)
  }

  Delete<P, T>(url: string, params: P, options?: UseFetchOptions<T>) {
    return this.request(url, 'DELETE', params, options)
  }
}

const httpRequest = new HttpRequest()

export default httpRequest
